#pragma once
#include <iostream>
#include <vector>
#include <pthread.h>
#include <semaphore.h>
#include "SmartMutex.hpp"

using namespace std;

const int defaultsize = 5;

template <class T>
class RQueue
{
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t &sem)
    {
        sem_post(&sem);
    }

public:
    RQueue(int size = defaultsize)
        : _q(size), _size(size), _p_index(0), _c_index(0)
    {
        sem_init(&_space_sem, 0, size);
        sem_init(&_date_sem, 0, 0);

        pthread_mutex_init(&_p_mutex, nullptr);
        pthread_mutex_init(&_c_mutex, nullptr);
    }

    void Push(const T &in)
    {

        P(_space_sem);

        { // 生产数据
            SmartMutex smartmutx(&_p_mutex);
            _q[_p_index] = in;
            _p_index++;
            _p_index %= _size;
        }

        V(_date_sem);
    }

    void Pop(T *out)
    {
        P(_date_sem);

        {
            // 消费数据
            SmartMutex smartmutx(&_c_mutex);
            *out = _q[_c_index];
            _c_index++;
            _c_index %= _size;
        }

        V(_space_sem);
    }

    ~RQueue()
    {
        sem_destroy(&_space_sem);
        sem_destroy(&_date_sem);

        pthread_mutex_destroy(&_p_mutex);
        pthread_mutex_destroy(&_c_mutex);
    }

private:
    vector<T> _q;
    size_t _size;

    sem_t _space_sem;
    sem_t _date_sem;

    int _p_index;
    int _c_index;

    pthread_mutex_t _p_mutex;
    pthread_mutex_t _c_mutex;
};